package com.teng.smartdrawer;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.teng.smartdrawer.adapter.DetailAdapter;
import com.teng.smartdrawer.adapter.MenuAdapter;
import com.teng.smartdrawer.bean.Component;
import com.teng.smartdrawer.bean.Part;
import com.teng.smartdrawer.bean.PopWindowMenu;
import com.teng.smartdrawer.listener.SwpipeListViewOnScrollListener;
import com.teng.smartdrawer.parser.DataConstants;
import com.teng.smartdrawer.parser.DataParser;
import com.teng.smartdrawer.popUtils.ScreenUtils;
import com.teng.smartdrawer.utils.CustomDialog;
import com.teng.smartdrawer.view.SwipeMenuLoadMoreListView;
import com.teng.smartdrawer.view.swipelistview.SwipeMenu;
import com.teng.smartdrawer.view.swipelistview.SwipeMenuCreator;
import com.teng.smartdrawer.view.swipelistview.SwipeMenuItem;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PartActivity extends AppCompatActivity implements View.OnClickListener , SwipeRefreshLayout.OnRefreshListener , CompoundButton.OnCheckedChangeListener {

    private List<Component> mData;
    private List<Part> componentList;
    private DetailAdapter adapter;
    private Dialog progressDialog , loadingDialog;
    private SwipeRefreshLayout refresh_layout;
    private LinearLayout option_menu;
    private Button cancel , delete;

    private Component component;
    private String option;
    private int number;
    private String id;
    private int activityType;
    private List<String> deleteList = new ArrayList<String>();;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_part);

        progressDialog = CustomDialog.createLoadingDialog(this, "正在操作...");
        initDialog();
        Intent intent = getIntent();
        id = intent.getStringExtra("id");
        String name = intent.getStringExtra("name");
        componentList = (List<Part>) intent.getSerializableExtra("componentList");
        activityType = intent.getIntExtra("type" , -1);


        ActionBar actionBar = getSupportActionBar();

        //显示返回图表
        actionBar.setDisplayHomeAsUpEnabled(true);

        //设置ActionBar左边默认的图标是否可用
        actionBar.setDisplayUseLogoEnabled(true);

        // 显示窗口标题
        actionBar.setDisplayShowTitleEnabled(true);

        actionBar.setTitle(name);

        option_menu = (LinearLayout) findViewById(R.id.option_menu);

        cancel = (Button) findViewById(R.id.cancel_action);
        cancel.setOnClickListener(this);

        delete = (Button) findViewById(R.id.delete_action);
        delete.setOnClickListener(this);

        TextView open_all_drawer = (TextView) findViewById(R.id.open_all_drawer);
        open_all_drawer.setOnClickListener(this);

        mData = new ArrayList<Component>();

        ListView listView = (ListView) findViewById(R.id.lv);

        View footer = LayoutInflater.from(this).inflate(R.layout.footer , null);

        listView.addFooterView(footer);

        refresh_layout = (SwipeRefreshLayout) findViewById(R.id.refresh_layout);

        listView.setOnScrollListener(new SwpipeListViewOnScrollListener(refresh_layout));

        refresh_layout.setColorSchemeResources(R.color.black, R.color.google_blue,
                R.color.google_yellow, R.color.google_blue, R.color.google_yellow);

        refresh_layout.setDistanceToTriggerSync(500);   // 下拉刷新的距离

        refresh_layout.setOnRefreshListener(this);

        refresh_layout.post(new Runnable() {
            @Override
            public void run() {
                refresh_layout.setRefreshing(true);
            }
        });

        adapter = new DetailAdapter(mData , this);

        adapter.setOnCountChangeListener(this);

        adapter.setItemCheckedListener(this);

        listView.setAdapter(adapter);

        Log.e("onekeyO" , id);

        // 模块详情和柜子详情
        if (activityType == 0) {
            open_all_drawer.setVisibility(View.GONE);
            DataParser.getComponentDetailList(this, handler, id);
        }else if(activityType == 1){
            open_all_drawer.setVisibility(View.VISIBLE);
            DataParser.getModuleDetailList(this, handler, id);
            adapter.setRecommendType(1);
        }else {
            open_all_drawer.setVisibility(View.GONE);
            Toast.makeText(this , "参数错误" , Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        if (activityType == 0){
            // 零器件才添加
            getMenuInflater().inflate(R.menu.menu_component , menu);
        }

        return super.onCreateOptionsMenu(menu);
    }

    private void initDialog(){
        loadingDialog = new Dialog(this , R.style.defind_dialog);

        LayoutInflater inflater = LayoutInflater.from(this);
        View v = inflater.inflate(R.layout.subscribe_menu_popwindow, null);
        ListView mMenuListView = (ListView) v.findViewById(R.id.menu_listview);

        LinearLayout menu_linearlayout = (LinearLayout) v.findViewById(R.id.menu_linearlayout);
        menu_linearlayout.setOnClickListener(this);

        ArrayList<PopWindowMenu> list = new ArrayList<PopWindowMenu>();

        list.add(new PopWindowMenu(0, 0, "编辑"));
        list.add(new PopWindowMenu(0, 0, "添加零器件"));

        MenuAdapter mMenuA = new MenuAdapter(this, list);
        mMenuListView.setAdapter(mMenuA);

        Window window = loadingDialog.getWindow();
        window.setGravity(Gravity.BOTTOM);

        loadingDialog.setCancelable(true);// 不可以用“返回键”取消
        loadingDialog.setContentView(v);// 设置布局
        WindowManager.LayoutParams lp = loadingDialog.getWindow().getAttributes();
        lp.width = ScreenUtils.getScreenWidth(this); // 设置宽度
        loadingDialog.getWindow().setAttributes(lp);

        mMenuListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                loadingDialog.dismiss();

                if (position == 0){
                    adapter.switchEditMode();
                    option_menu.setVisibility(View.VISIBLE);
                }else if(position == 1) {
                    Intent intent = new Intent(PartActivity.this, AddComponentActivity.class);
                    intent.putExtra("componentList", (Serializable) componentList);
                    startActivityForResult(intent, 1);
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (data != null) {
            List<Component> addComponentList = (ArrayList<Component>) data.getSerializableExtra("addComponentList");

            for (Component c : addComponentList) {

                if (id.equals(c.getM_tid())){

                    mData.add(c);

                }

                adapter.notifyDataSetChanged();

            }
        }

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if(item.getItemId() == android.R.id.home)
        {
            // TODO actionBar返回处理
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);

    }

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            int what = msg.what;
            if (progressDialog != null) {
                progressDialog.dismiss();
            }
            switch (what) {
                case DataConstants.GET_COMPONENT_DETAIL_SIGN:
                    // TODO 获取零器件详情
                    refresh_layout.setRefreshing(false);

                    List<Component> data = (List<Component>) msg.obj;

                    mData.clear();
                    mData.addAll(data);
                    adapter.notifyDataSetChanged();

                    break;

                case DataConstants.GET_COMPONENT_OPTION_SIGN:
                    // TODO 存取零器件
                    int status = (int) msg.obj;

                    if (status == 200){

                        if (option.equals("put")){
                            int m_number = component.getM_number();
                            component.setM_number(m_number + number);

                        }else if(option.equals("get")){
                            int m_number = component.getM_number();
                            component.setM_number(m_number - number);

                        }else if(option.equals("delete")){

                            for (int i = 0; i < deleteList.size(); i++) {
                                String del = deleteList.get(i);
                                for (int j = 0 ; j < mData.size() ; j++) {
                                    Component c = mData.get(j);
                                    if (c.getM_id().equals(del)){
                                        mData.remove(j);
                                        continue;
                                    }
                                }
                            }
                        }

                        adapter.notifyDataSetChanged();
                    }

                    break;

                case DataConstants.MODULE_OPEN_CABINET:
                    // TODO 一键打开柜子
                    int obj = (int) msg.obj;

                    if (obj == 200){
                        Toast.makeText(PartActivity.this , "打开成功" , Toast.LENGTH_SHORT).show();

                        for (Component component : mData) {
                            component.setM_number( component.getM_number() - component.getCount());
                        }

                        adapter.notifyDataSetChanged();

                    }else {
                        Toast.makeText(PartActivity.this , "打开失败" , Toast.LENGTH_SHORT).show();
                    }

                    break;
            }

            return false;

        }
    });


    @Override
    public void onClick(View v) {
        int clickId = v.getId();


        switch (clickId){

            case R.id.cancel_action:
                option_menu.setVisibility(View.GONE);
                adapter.switchEditMode();
                break;

            case R.id.delete_action:
                option_menu.setVisibility(View.GONE);
                adapter.switchEditMode();
                String deleteIds = "";

                deleteList.clear();

                for (Component c : mData) {
                    if (c.isChecked()){
                        deleteList.add(c.getM_id());
                    }
                }

                for (int i = 0; i < deleteList.size(); i++) {
                    if (i == 0) {
                        deleteIds += deleteList.get(i);
                    }else {
                        deleteIds = deleteIds+ "," + deleteList.get(i);
                    }
                }

                progressDialog.show();
                option = "delete";
                DataParser.componentOperateResult(this, handler, "delete", deleteIds, "");

                break;

            case R.id.reduce:
                int pos = (int) v.getTag();
                component = mData.get(pos);
                component.setCount(component.getCount() - 1);
                component.setM_neednum(component.getM_neednum() - 1);
                adapter.notifyDataSetChanged();
                break;

            case R.id.add:
                int add_pos = (int) v.getTag();
                component = mData.get(add_pos);

//                if (component.getCount() + 1 > component.getM_number()){
//                    Toast.makeText(PartActivity.this , "数量不足" , Toast.LENGTH_SHORT).show();
//                    return;
//                }
                component.setCount(component.getCount() + 1);
                component.setM_neednum(component.getM_neednum() + 1);
                adapter.notifyDataSetChanged();

                break;

            case R.id.dt_put:
                int put_pos = (int) v.getTag();
                component = mData.get(put_pos);
                option = "put";
                number = component.getCount();
                if (number == 0){
                    Toast.makeText(PartActivity.this , "数量不能等于0" , Toast.LENGTH_SHORT).show();
                    return;
                }
                progressDialog.show();
                DataParser.componentOperateResult(this, handler, "add", component.getM_id(), component.getCount() + "");
                break;

            case R.id.dt_get:
            case R.id.get_com:
                int get_pos = (int) v.getTag();
                component = mData.get(get_pos);
                option = "get";
                number = component.getCount();

                if (number == 0){
                    Toast.makeText(PartActivity.this , "数量不能等于0" , Toast.LENGTH_SHORT).show();
                    return;
                }

                if (number > component.getM_number()){
                    Toast.makeText(PartActivity.this , "数量不足" , Toast.LENGTH_SHORT).show();
                    return;
                }

                progressDialog.show();
                DataParser.componentOperateResult(this, handler, "reduce", component.getM_id(), component.getCount() + "");
                break;
            case R.id.menu_linearlayout:

                if(loadingDialog != null && loadingDialog.isShowing())
                    loadingDialog.dismiss();

                break;

            case R.id.open_all_drawer:
                // TODO 打开所有的柜子

                if(adapter.isCanOpenAllDrawer()){

                    Map<String , Integer> map = new HashMap<>();

                    JSONArray jsonArray = new JSONArray();


                    for (int i = 0; i < mData.size(); i++) {
                        Component component = mData.get(i);
                        JSONObject jsonObj = new JSONObject();
                        try {
                            jsonObj.put("id", component.getM_id());
                            jsonObj.put("num", component.getM_neednum());
                            jsonArray.put(jsonObj);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    DataParser.onekeyOPen(PartActivity.this , handler , jsonArray.toString() ,  id);
                    progressDialog.show();
                    Toast.makeText(PartActivity.this , "打开成功" , Toast.LENGTH_SHORT).show();
                }else {
                    Toast.makeText(PartActivity.this , "有器件短缺，请单独单开" , Toast.LENGTH_SHORT).show();
                }

                break;
            default:
                break;

        }
    }

    public void component_menu(MenuItem item) {
        loadingDialog.show();
    }

    @Override
    public void onRefresh() {
        // 模块详情和柜子详情
        if (activityType == 0) {
            DataParser.getComponentDetailList(this, handler, id);
        }else if(activityType == 1){
            DataParser.getModuleDetailList(this, handler, id);
        }else {
            Toast.makeText(this , "参数错误" , Toast.LENGTH_SHORT).show();
        }
    }


    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

        if (buttonView.getId() == R.id.checkbox){

            Object tag = buttonView.getTag();

            if (tag != null && tag instanceof Integer) {
                int pos = (int) tag;

                Component com = mData.get(pos);

                com.setChecked(isChecked);

                adapter.notifyDataSetChanged();
            }

        }

    }


    /**
     * 将Map转化为Json
     *
     * @param map
     * @return String
     */
    public static <T> String mapToJson(Map<String, T> map) {
        Gson gson = new Gson();
        String jsonStr = gson.toJson(map);
        return jsonStr;
    }

}
